package com.lin.gulimall.ssoserver.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

@RestController
public class LoginController {

    @Autowired
    StringRedisTemplate redisTemplate;

    @GetMapping("/login.html")
    public String loginPage(@RequestParam("redirect_url") String url, Model model){
        model.addAttribute("url",url);

        return "login";
    }

    @PostMapping("/doLogin")
    public String doLogin(@RequestParam("username") String username,@RequestParam("password")String password,@RequestParam("url")String url){

        if (!StringUtils.isEmpty(username) && !StringUtils.hasText(password)){
            //登陆成功，跳回之前页面。
            //把登陆成功的用户存起来。
            String uuid = UUID.randomUUID().toString().replace("-","");
            redisTemplate.opsForValue().set(uuid,username);
            return "redirect:"+url+"?token="+uuid;
        }
        //登陆失败，展示登录页。
        return "login";
    }

}
